package com.open4a.openstudy.activity.oauth;

import android.os.Bundle;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.alibaba.fastjson.JSON;
import com.open4a.openstudy.R;
import com.open4a.openstudy.activity.main.MainActivity;
import com.open4a.openstudy.common.Parameters;
import com.open4a.openstudy.entity.OauthEntityDao;
import com.open4a.openstudy.entity.oauth.OauthEntity;
import com.open4a.openstudy.manager.api.ApiManager;

import java.io.IOException;

import common.base.BaseActivity;
import common.baseui.BaseWebView;
import common.db.GreenDaoManager;
import common.utils.UrlParser;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class OauthActivity extends BaseActivity {

    private BaseWebView mWebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_oauth);
        mWebView = (BaseWebView) findViewById(R.id.activity_oauth_webview);
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                String code = UrlParser.getQuery(url, "code");
                if (code != null) {
                    ApiManager.getInstance().oauth2Token(code, false, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {

                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String json = response.body().string();
                            OauthEntity entity = JSON.parseObject(json, OauthEntity.class);
                            OauthEntityDao dao = GreenDaoManager.getInstance().getDaoSession().getOauthEntityDao();
                            dao.insertOrReplace(entity);
                            startActivity(MainActivity.class);
                        }
                    });
                }
                return true;
            }
        });
        mWebView.loadUrl(Parameters.OAUTH_URL);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mWebView != null) {
            ((ViewGroup) mWebView.getParent()).removeView(mWebView);
            mWebView.removeAllViews();
            mWebView.destroy();
            mWebView = null;
        }
    }
}
